package net.didactylos.helpline.action;

import org.hibernate.Session;

import net.didactylos.helpline.data.*;
import net.didactylos.helpline.stripes.bean.HelplineActionBean;
import net.didactylos.helpline.stripes.security.Capabilities;
import net.didactylos.helpline.stripes.security.Secured;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.validation.*;

public class SetupAction extends HelplineActionBean
{
	@Validate(required=true)
	private String username;
	
	public String getUsername()
	{
		return username;
	}

	public void setUsername(String username)
	{
		this.username = username;
	}

	@DontValidate
	@DefaultHandler
	@Secured(Capabilities.NONE)
	public Resolution view()
	{
		username = "admin";
		return new ForwardResolution("setup.jspx");
	}
	
	@Secured(Capabilities.NONE)
	public Resolution setup()
	{
		Session session = getContext().getSession();
		
		// Check for empty user table
		Long userCount = (Long) session.createQuery("select count(*) from User").uniqueResult();
		
		if (userCount == 0)
		{
			Role role = new Role();
			role.setName("Administrator");
			role.setCapabilities(Capabilities.ALL.capabilities());
			User user = new User();
			user.setUsername(username);
			user.setEmailAddress("");
			user.setFirstNames("");
			user.setLastName("");
			user.setRole(role);
			String password = user.generatePassword(10);
			getContext().getMessages().add(new LocalizableMessage("passwordGeneratedMessage", username, password));
			
			session.save(role);
			session.save(user);
			       
	        // Log in automatically.
	        getContext().setUser(user);
		}
        
		return new RedirectResolution("/");
	}
}
